/*
 * cme-refDialog v1.0
 * 参照框
 * *多选 v1.0
 * *单选 v1.1
 * 
 * 依赖：
 * jquery 1.11.3 核心工具类库，本工具是作为jquery插件编写的
 * art-template-4.12.2 js模板工具，可自行修改代码替换
 * layer-v2.2 异步加载时等待动画，自行修改数据加载处的动画处理
 * bootstrap.jDialog-v1.1 基于bootstrap写的一个modal封装
 *  
 *
 * @copyright 2017 huangyi 
 */
;
(function ($) {

    function CmeRefDialog(opts) {
        var $this = this;
        var defaultSetting = {
            id: 'cmeRefDialog', //随意取，主要作用是生成不重复的对话框，input绑定模式不用填
            title: '选择', //弹出框名称
            keyField: 'id', //表格中主键（唯一表示）字段名称
            textField: 'text', //表格中用来显示的字段名称
            url: '', //列表数据获取的url
            detailUrl: '', //elShow容器和已选取表格在已有数据的情况下，初始化查询的url，url中参数自动加入keyField=id1,id2,id3
            table: {
                row: 5, //表格一页显示多少行
                columns: [] //构造表格用的{field:ajax传来的字段名字,text:显示在表头上的名字}
            },
            data : null,//value字符串，用逗号隔开
            type: 'multi',//single,multi
            elShow: null, //对象，点击【确认】后获取的显示文字，用逗号隔开
            elValue: null, //对象，点击【确认】后获取的key值，用逗号隔开
            event: {
                //重写【确认】按钮事件，elShow和elValue将失去作用，参数data是选中的每一行的数据组成的数组
                onOk: function (data) {
                    var showAry = [];
                    var valueAry = [];
                    if (data && data.length > 0) {
                        for (var i in data) {
                            showAry.push(data[i][$this.setting.textField]);
                            valueAry.push(data[i][$this.setting.keyField]);
                        }

                        if ($this.setting.elShow) {
                            $this.setValue2El($this.setting.elShow, showAry.join(','));
                        }
                        if ($this.setting.elValue) {
                            $this.setValue2El($this.setting.elValue, valueAry.join(','));
                        }
                    }
                    return true;
                }
            }
        }
        this.setting = $.extend(true, {}, defaultSetting, opts);
        this.store = [];
        this.ajaxDataCache;
        this.dataTablePager;
        this.storeTablePager;

        this.refDialogBtns = [{
            id: 'btnOk',
            cls: 'btn btn-primary',
            text: '确定',
            callback: function () {
                $this.btnCallbackWrapper();
            }
        }, {
            id: 'btnCancel',
            cls: 'btn btn-default',
            text: '取消',
            ref: 'close'

        }];


        return this;
    }

    CmeRefDialog.prototype.show = function () {
        var $this = this;
        jDialog.show(this.setting.id, this.setting.title, this.buildHtml(), this.refDialogBtns, true, function () {
            $this.initBtn();
            $this.initStore();
            $this.initTable();
        }, false);
    }

    CmeRefDialog.prototype.init = function () {
        //插入elShow的html结构
        var elShowHtml = this.buildElShow();
        var $this = this;
        this.setting.elValue.after(elShowHtml);
        $('#' + this.setting.id + 'ElShowBtnOpen').on('click', function () {
            $this.show();
        });
        this.setting.elShow = $('#' + this.setting.id + 'ElShow');
        this.bind();
    }

    CmeRefDialog.prototype.buildElShow = function () {
        var html = '' +
            '<div class="input-group">' +
            '        <input type="text" class="form-control" id="' + this.setting.id + 'ElShow">' +
            '        <div class="input-group-btn">' +
            '           <button type="button" class="btn btn-default" id="' + this.setting.id + 'ElShowBtnOpen">' +
            '                <span class="glyphicon glyphicon-search"></span>' +
            '            </button>' +
            '        </div>' +
            '    </div>';
        return html;
    }

    CmeRefDialog.prototype.inAjaxDataCache = function (key) {
        if (this.ajaxDataCache && this.ajaxDataCache.length > -1) {
            for (var i in this.ajaxDataCache) {
                if (this.ajaxDataCache[i][this.setting.keyField] == key) {
                    return true;
                }
            }
        }
        return false;
    }

    CmeRefDialog.prototype.removeStoreByKey = function (key) {
        if (this.store) {
            var index = -1;
            for (var i = 0; i < this.store.length; i++) {
                if (this.store[i][this.setting.keyField] == key) {
                    index = i;
                    break;
                }
            }
            if (index > -1) {
                this.store.splice(index, 1);
            }
        }
        this.storeTablePager.setData(this.store);
        //如果删除的数据在列表中有显示，也同步去掉勾
        if (this.inAjaxDataCache(key)) {
            $('input:checkbox[value="' + key + '"]', '#' + this.setting.id + 'DataTable tbody').prop('checked', false);
        }
    }

    CmeRefDialog.prototype.add2Store = function (rowData) {
        if(this.setting.type!='multi'){
            this.store = [];
        }
        this.store.push(rowData);
        this.storeTablePager.setData(this.store);
    }

    CmeRefDialog.prototype.getOriginValue = function () {
        return this.store;
    }

    CmeRefDialog.prototype.getKeyValue = function () {
        var keys = [];
        var orginValues = this.getOriginValue();
        for (var i in orginValues) {
            keys.push(orginValues[i][this.setting.keyField]);
        }
        return keys;
    }

    CmeRefDialog.prototype.btnCallbackWrapper = function () {
        if (this.setting.event.onOk(this.getOriginValue())) {
            $('#' + this.setting.id).modal('hide');
        }

    }

    CmeRefDialog.prototype.initBtn = function () {
        //搜索
        var $this = this;
        $('#' + this.setting.id + 'BtnSearch').on('click', function () {
            $this.dataTablePager.reload();
        });
        //tab
        $('#' + this.setting.id + 'TabTable').on('click', function () {
            $(this).addClass('active');

            $('#' + $this.setting.id + 'TabStore').removeClass('active');
            $('#' + $this.setting.id + 'DataTablePanel').show();
            $('#' + $this.setting.id + 'StoreTablePanel').hide();
        });
        $('#' + this.setting.id + 'TabStore').on('click', function () {
            $(this).addClass('active');
            $('#' + $this.setting.id + 'TabTable').removeClass('active');
            $('#' + $this.setting.id + 'DataTablePanel').hide();
            $('#' + $this.setting.id + 'StoreTablePanel').show();
        });

    }

    CmeRefDialog.prototype.initTable = function () {
        var $this = this;
        //数据表加载
        this.dataTablePager = $('#' + this.setting.id + 'DataTable').pager({
            tplId: $this.setting.id + 'DataTableTpl',
            url: $this.setting.url,
            pagingTplId: $this.setting.id + 'DataTablePageTpl',
            pagingId: $this.setting.id + 'DataTablePage',
            pagingNum: 2,
            animation: true,
            startField: 'pageNum',
            numField: 'pageSize',
            params: function () {
                var searchValue = $('#' + $this.setting.id + 'ValueSearch').val();
                var param = {};
                param.pageSize = $this.setting.table.row;
                if (searchValue && searchValue != '') {
                    param.searchValue = searchValue;
                }
                return param;
            },
            event: {
                onDidLoaded: function (page, totalPage, data) {
                    $this.ajaxDataCache = data;

                },
                afterRender: function () {
                    if($this.setting.type=='multi'){
                        $('tr','#' + $this.setting.id + 'DataTable tbody').on('click',function(){
                            var checkbox = $('input:checkbox',this);
                            if(checkbox.is(':checked')){
                                $this.removeStoreByKey(checkbox.val());
                                $('input:checkbox',this).prop('checked',false);
                            }else{
                                $this.rowAdd2Store(checkbox.val());
                                $('input:checkbox',this).prop('checked',true);
                            }
                        });
                        //row checkbox
                        $('input:checkbox', '#' + $this.setting.id + 'DataTable tbody').on('click', function (e) {
                            if ($(this).is(':checked')) {
                                //添加到store
                                $this.rowAdd2Store($(this).val());
                            } else {
                                //remove from store
                                $this.removeStoreByKey($(this).val());
                            }
                            //阻止事件冒泡，防止tr被重复触发
                            e.stopPropagation();
                        });
                    }else{
                        
                        //row radio
                        $('input:radio', '#' + $this.setting.id + 'DataTable tbody').on('click', function () {
                                //添加到store
                                $this.rowAdd2Store($(this).val());
                                e.stopPropagation();
                               
                        });
                        $('tr','#' + $this.setting.id + 'DataTable tbody').on('click',function(){
                            $this.rowAdd2Store($('input:radio',this).val());
                            $('input:radio',this).prop('checked',true);
                        });
                    }
                    //page
                    $($this.setting.id + 'DataTablePageBtnPrev').on('click', function () {
                        $this.dataTablePager.prev();
                    });
                    $($this.setting.id + 'DataTablePageBtnNext').on('click', function () {
                        $this.dataTablePager.next();
                    });
                    $('a[role="' + $this.setting.id + 'PageNumber"]', '#' + $this.setting.id + 'Pagination').on('click', function () {
                        var pageNum = $(this).html();
                        $this.dataTablePager.go(pageNum);
                    });
                    //根据store中的反向勾选表格中的项
                    $this.store2Data();

                }
            }
        });

    }
    CmeRefDialog.prototype.rowAdd2Store = function(val){
        for (var i in this.ajaxDataCache) {
            if (this.ajaxDataCache[i][this.setting.keyField] == val) {
                this.add2Store(this.ajaxDataCache[i]);
                break;
            }
        }
    };

    CmeRefDialog.prototype.store2Data = function () {
        var $this = this;
        var originValues = this.getOriginValue();
        if(this.setting.type=='multi'){
            $("input:checkbox", '#' + this.setting.id + 'DataTable tbody').each(function () {
                var val = $(this).val();
                for (var i in originValues) {
                    if (val == originValues[i][$this.setting.keyField]) {
                        $(this).prop('checked', true);
                        break;
                    }
                }
            });
        }else{
            $("input:radio", '#' + this.setting.id + 'DataTable tbody').each(function () {
                var val = $(this).val();
                for (var i in originValues) {
                    if (val == originValues[i][$this.setting.keyField]) {
                        $(this).prop('checked', true);
                        break;
                    }
                }
            });
        }
    };

    CmeRefDialog.prototype.bind = function () {
        var $this = this;
        if (this.setting.elValue) {
            var values = this.setting.elValue.val();
            if (values) {
                var param = {};
                param[this.setting.keyField] = values;
                $.getJSON(this.setting.detailUrl, param, function (result) {
                    if (result && result.code == 'success') {
                        if ($this.setting.elShow) {
                            $this.setValue2El($this.setting.elShow, $this.getNames(result.data.data));
                        }
                    }
                });
            }
        }
    }

    CmeRefDialog.prototype.getNames = function (data) {
        var names = [];
        if (data) {
            for (var i in data) {
                names.push(data[i][this.setting.textField]);
            }
        }
        return names.join(',');
    }

    CmeRefDialog.prototype.loadRemoteStoreData = function () {
        var $this = this;
        if (this.setting.elValue) {
            var values = this.setting.elValue.val();
            $this.loadRemoteData(values);
        }else if(this.setting.data){
            $this.loadRemoteData(this.setting.data);
        }
    }

    CmeRefDialog.prototype.loadRemoteData = function(values){
        var $this = this;
        if (values) {
            var param = {};
            param[this.setting.keyField] = values;
            $.getJSON(this.setting.detailUrl, param, function (result) {
                if (result && result.code == 'success') {
                    $this.store = result.data.data;
                    $this.storeTablePager.setData($this.store);
                    $this.store2Data();
                }
            });
        }
    }

    CmeRefDialog.prototype.initStore = function () {
        var $this = this;
        this.store = [];
        //if elValue element has value, get value from remote by values
        this.loadRemoteStoreData();
        //数据表加载
        this.storeTablePager = $('#' + this.setting.id + 'StoreTable').pager({
            tplId: $this.setting.id + 'StoreTableTpl',
            pagingNum: 4,
            data: $this.store,
            animation: false,
            event: {

                afterRender: function () {
                    //row checkbox

                    $('a.' + $this.setting.id + 'StoreRowBtnDelete', '#' + $this.setting.id + 'StoreTable tbody').on('click', function () {
                        $this.removeStoreByKey($(this).attr('ref-data'));
                    });
                }
            }
        });
    }

    CmeRefDialog.prototype.buildDataTableHeadTpl = function () {
        var html = '<tr><th width="40">';
        if (this.setting.type == 'multi') {
            html += '<input type="checkbox" id="' + this.setting.id + 'DataTableBtnSelectAll"/>';
        }
        html += '</th>';
        for (var i in this.setting.table.columns) {
            html += '<th>';
            html += this.setting.table.columns[i].text;
            html += '</th>';
        }
        html += '</tr>';
        return html;
    }


    CmeRefDialog.prototype.buildDataTableBodyTpl = function () {
        var html = '<tr><td width="40">';
        if(this.setting.type == 'multi'){
            html +='<input type="checkbox" value="{{$value.' + this.setting.keyField + '}}"/>';
        }else{
            html +='<input type="radio" name="'+this.setting.id+'refDialogRadio" value="{{$value.' + this.setting.keyField + '}}"/>';
        }
        html +='</td>';
        for (var i in this.setting.table.columns) {
            html += '<td>';
            html += '{{$value.' + this.setting.table.columns[i].field + '}}';
            html += '</td>';
        }
        html += '</tr>';
        return html;
    }

    CmeRefDialog.prototype.buildStoreTableHeadTpl = function () {
        var html = '<tr>';
        for (var i in this.setting.table.columns) {
            html += '<th>';
            html += this.setting.table.columns[i].text;
            html += '</th>';
        }
        html += '<th width=“60">操作</th>';
        html += '</tr>';
        return html;
    }

    CmeRefDialog.prototype.buildStoreTableBodyTpl = function () {
        var html = '<tr>';
        for (var i in this.setting.table.columns) {
            html += '<td>';
            html += '{{$value.' + this.setting.table.columns[i].field + '}}';
            html += '</td>';
        }
        html += '<td><a href="javascript:void(0);" class="' + this.setting.id + 'StoreRowBtnDelete" ref-data="{{$value.' + this.setting.keyField + '}}">删除</a></td>';
        html += '</tr>';
        return html;
    }


    CmeRefDialog.prototype.buildHtml = function () {
        var html = '<div class="container-fluid">' +
            '        <div class="row">' +
            '            <ul class="nav nav-tabs">' +
            '                <li role="presentation" id="' + this.setting.id + 'TabTable" class="active"><a href="#">列表</a></li>';
            if(this.setting.type=='multi'){
                html+='                <li role="presentation" id="' + this.setting.id + 'TabStore"><a href="#">已选取</a></li>';
            }
            html+='            </ul>' +
            '        </div>' +
            '		<div id="' + this.setting.id + 'DataTablePanel">' +
            '        <div class="row m-top-10">' +
            '            <div class="input-group">' +
            '                <input type="text" class="form-control" id="' + this.setting.id + 'ValueSearch" placeholder="搜索关键字">' +
            '                <span class="input-group-btn">' +
            '		        <button class="btn btn-default" type="button" id="' + this.setting.id + 'BtnSearch">搜索</button>' +
            '		      </span>' +
            '            </div>' +
            '        </div>' +
            '        <div class="row m-top-10">' +
            '			<table class="table table-hover" id="' + this.setting.id + 'DataTable">' +
            '			</table>' +
            '        </div>' +
            '        <div class="row">' +
            '        	<div class="col-sm-6 col-sm-offset-3" id="' + this.setting.id + 'DataTablePage">' +
            '        	</div>' +
            '        </div>' +
            '		</div>' +
            '		<div id="' + this.setting.id + 'StoreTablePanel" style="display:none">' +
            '			<table class="table table-hover" id="' + this.setting.id + 'StoreTable">' +
            '			</table>' +
            '		</div>' +
            '    </div>';
        html += '<script type="text/template" id="' + this.setting.id + 'DataTableTpl">';
        html += this.buildDataTableTpl();
        html += '</script>';
        html += '<script type="text/template" id="' + this.setting.id + 'DataTablePageTpl">';
        html += this.buildPageTpl();
        html += '</script>';
        html += '<script type="text/template" id="' + this.setting.id + 'StoreTableTpl">';
        html += this.buildStoreTableTpl();
        html += '</script>';
        return html;
    }

    CmeRefDialog.prototype.buildDataTableTpl = function () {
        var html = '';
        html += '<thead>' + this.buildDataTableHeadTpl() + '</thead>';
        html += '<tbody>';
        html += '{{each data}}';
        html += this.buildDataTableBodyTpl();
        html += '{{/each}}';
        html += '</tbody>';
        return html;
    }

    CmeRefDialog.prototype.buildStoreTableTpl = function () {
        var html = '';
        html += '<thead>' + this.buildStoreTableHeadTpl() + '</thead>';
        html += '<tbody>';
        html += '{{each data}}';
        html += this.buildStoreTableBodyTpl();
        html += '{{/each}}';
        html += '</tbody>';
        return html;
    }

    CmeRefDialog.prototype.buildPageTpl = function () {
        var html = '<nav aria-label="Page navigation">' +
            '	                <ul class="pagination " id="' + this.setting.id + 'Pagination">' +
            '	                    <li>' +
            '	                        <a href="#" aria-label="Previous" id="' + this.setting.id + 'DataTablePageBtnPrev">' +
            '						        <span aria-hidden="true">&laquo;</span>' +
            '						      </a>' +
            '	                    </li>' +
            '						{{each data}}' +
            '						<li class="{{if start==$value}} active{{/if}}"><a href="javascript:void(0);" class="{{if start==$value}}active{{/if}}" role="' + this.setting.id + 'PageNumber" >{{$value}}</a></li>' +
            '						{{/each}}' +
            '	                    <li>' +
            '	                        <a href="#" aria-label="Next" id="' + this.setting.id + 'DataTablePageBtnNext">' +
            '						        <span aria-hidden="true">&raquo;</span>' +
            '						      </a>' +
            '	                    </li>' +
            '	                </ul>' +
            '	            </nav>'
        return html;
    }

    CmeRefDialog.prototype.setValue2El = function (el, value) {
        var tag = '';
        if (el.length >= 1) {
            tag = el[0].type;
        } else {

            tag = el.type;
        }
        switch (tag) {
            case 'checkbox':
                if (el.val() == value) {
                    el.prop('checked', true);
                } else {
                    el.prop('checked', false);
                }
                break;
            case 'radio':
                if (el.val() == value) {
                    el.prop('checked', true);
                } else {
                    el.prop('checked', false);
                }
                break;
            case 'text':
            case 'hidden':
                el.val(value);
                break;
            default:
                el.html(value);
        }
    }

    //用法1：直接调用show打开选择框
    $.extend({
        refDialog: function (opts) {
            var cmeRefDialog = new CmeRefDialog(opts);
            return cmeRefDialog;
        }
    });
    //用法2：绑定value控件，在value控件后插入一个input控件作为文字显示
    $.fn.refDialog = function (opts) {
        function guid() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = Math.random() * 16 | 0,
                    v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        }

        return this.each(function () {
            //绑定值的存储节点
            opts.elValue = $(this);
            //没有ID的，生成guid作为ID
            var elId = $(this).attr('id');
            if (elId) {
                opts.id = elId + 'refDialog';
            } else {
                opts.id = guid() + 'refDialog';
            }
            var cmeRefDialog = new CmeRefDialog(opts);
            cmeRefDialog.init();
        });
    }

})(jQuery);